package com.fpc.cn.springbootutil.mybatisLog;


import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.core.type.classreading.AnnotationMetadataReadingVisitor;

import java.util.ArrayList;
import java.util.List;

/**
 * @date 2025/4/27
 * @author fupengcheng
 * 自定义条件配置，实现拦截器可配置
 * 配置项名称：dx.mybatis.interceptor.types 可选值：all、update、query、空值（不设置，等价于all）
 */
public class MpInterceptorCondition implements Condition {
    public final static String INTERCEPTOR_TYPE_UPDATE = "update";
    public final static String INTERCEPTOR_TYPE_QUERY = "query";
    public final static String INTERCEPTOR_TYPE_ALL = "all";

    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        //配置项解析结果
        List<String> typeResolveResult = new ArrayList<>();
        //验证是否创建拦截器
        return this.charge(typeResolveResult, annotatedTypeMetadata);
    }

    public boolean charge(List<String> types, AnnotatedTypeMetadata annotatedTypeMetadata){
        //未设置时默认通过
        if(types.isEmpty() || types.contains(INTERCEPTOR_TYPE_ALL))
            return true;
        //无法获取目标对象时，默认通过
        if(!(annotatedTypeMetadata instanceof AnnotationMetadataReadingVisitor))
            return true;
        String typeClassName = ((AnnotationMetadataReadingVisitor) annotatedTypeMetadata).getClassName();
        //存在指定的，则判断是否设置
        if(MybatisUpdateInterceptor.class.getName().equalsIgnoreCase(typeClassName))
            return types.contains(INTERCEPTOR_TYPE_UPDATE);
        else if(MybatisQueryInterceptor.class.getName().equalsIgnoreCase(typeClassName))
            return types.contains(INTERCEPTOR_TYPE_QUERY);
        //为找到设置项时，不通过
        return false;
    }
}
